package myaction.admin.studentinfo;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class StudentDeleteAction extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("s_id");
        try {
            Connection conn = DbUtil.getConn();
            //查看t_opt表中
            String sql1 = "select * from t_opt where o_student_id=?";
            PreparedStatement ps = conn.prepareStatement(sql1);
            ps.setString(1, id);
            ResultSet re = ps.executeQuery();
            //查询学生是否在选完课的课程中
            //如果学生已经选完课则无法删除
            if (re.next()) {
                System.out.println("id为" + id + "的学生已经在一个课程中，无法删除！");
                re.close();
                ps.close();
                conn.close();
                response.sendRedirect("StudentDeleteAction");
            } else {
                String sql2 = "delete from t_students where s_id=?;";
                PreparedStatement pstmt = conn.prepareStatement(sql2);
                pstmt.setString(1, id);
                pstmt.executeUpdate();
                pstmt.close();
                conn.close();
                System.out.println("id为" + id + "的学生已被删除！");
                response.sendRedirect("StudentFindAll");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
